package io.renren.utils.util.db.connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/** 
 * Get DataSource with JNDI from directory server. Need to work with JTA
 * @author Clark Liu
 *
 */
public class JndiDataSourceFactory implements DataSourceFactory {
	public static final String DEFAULT_NAME_PREFIX = "java:comp/env/jdbc/";

	private String namePrefix = DEFAULT_NAME_PREFIX;
	private String defaultDS = null;
	
	public JndiDataSourceFactory() {
		super();
	}

	public DataSource getDataSource(String sourceName) {
		try {
			Context context = new InitialContext();
			DataSource ds = (DataSource) context.lookup(namePrefix + sourceName);
			return ds;
		} catch (NamingException ex) {
			throw new RuntimeException("Can't find datasource '" + namePrefix + " " + sourceName + "'.", ex);
		}
	}

	/**
	 * @return
	 */
	public String getNamePrefix() {
		return namePrefix;
	}

	/**
	 * @param string
	 */
	public void setNamePrefix(String string) {
		namePrefix = string;
	}

	@Override
	public String getDefaultDS() {
		return defaultDS;
	}

	@Override
	public void setDefaultDS(String defaultDS) {
		this.defaultDS = defaultDS;		
	}

}
